package nix.demo2.web.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nix.commons.CommonUtils;
import nix.demo2.domain.User;
import nix.demo2.service.UserException;
import nix.demo2.service.UserService;

public class RegisterServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		UserService userService = new UserService();
		// 表单数据封装到User对象中
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);

		Map<String, String> errors = new HashMap<String, String>();

		if (form.getUsername() == null || form.getUsername().trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if (form.getUsername().length() < 2
				|| form.getUsername().length() > 16) {
			errors.put("username", "用户名长度必须在2-16位之间！");
		}

		if (form.getPassword() == null || form.getPassword().trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if (form.getPassword().length() < 3
				|| form.getPassword().length() > 16) {
			errors.put("password", "密码长度必须在3-16位之间！");
		}

		String sessionVCode = (String) request.getSession().getAttribute(
				"session_vcode");
		if (form.getVerifyCode() == null
				|| form.getVerifyCode().trim().isEmpty()) {
			errors.put("verifyCode", "验证码不能为空！");
		} else if (!form.getVerifyCode().equalsIgnoreCase(sessionVCode)) {
			errors.put("verifyCode", "验证码错误！");
		}

		if (errors != null && errors.size() > 0) {
			request.setAttribute("errors", errors);
			// 数据回显
			request.setAttribute("user", form);
			request.getRequestDispatcher("/demo2/register.jsp").forward(
					request, response);
			return;
		}

		try {
			userService.register(form);
			response.getWriter().print(
					"<h3>注册成功！<a href='" + request.getContextPath()
							+ "/demo2/login.jsp'>去登陆</a></h3>");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			// 数据回显
			request.setAttribute("user", form);
			request.getRequestDispatcher("/demo2/register.jsp").forward(
					request, response);
		}
	}
}
